package com.hnucm.cooklife.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ToastUtils;
import com.hnucm.cooklife.R;
import com.hnucm.cooklife.adapter.RecomAdapter;
import com.hnucm.cooklife.base.BaseFragment;
import com.hnucm.cooklife.base.Utils;
import com.hnucm.cooklife.base.utils.Constant;
import com.hnucm.cooklife.base.utils.LoginUtils;
import com.hnucm.cooklife.bean.base.Event;
import com.hnucm.cooklife.bean.db.Dish;
import com.hnucm.cooklife.bean.me.ToAddCollectData;
import com.hnucm.cooklife.contract.recom.Contract;
import com.hnucm.cooklife.presenter.home.RecomPresenter;
import com.hnucm.cooklife.ui.activity.DishDetailActivity;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class RecomFragment extends BaseFragment<Contract.IRecomView, RecomPresenter> implements Contract.IRecomView,
        com.scwang.smartrefresh.layout.listener.OnLoadMoreListener,
        com.scwang.smartrefresh.layout.listener.OnRefreshListener
{
    private Context mContext;
    private RecomAdapter mRecomAdapter;
    private List<Dish> mDishList = new ArrayList<>();
    private int userId;
    private int currentPage = 1;

    @BindView(R.id.recom_recycler)
    RecyclerView mRecyclerView;

    @BindView(R.id.refresh_layout)
    SmartRefreshLayout mSmartRefreshLayout;

    @BindView(R.id.layout_error)
    ViewGroup mLayoutError;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);

    }

    @Override
    protected int getContentViewId() {
        return R.layout.recom_fragment;
    }

    @Override
    protected void init() {
        mContext = getContext().getApplicationContext();
        userId = LoginUtils.getLoginId();
        initAdapter();
        mPresenter.loadDish(currentPage);
        mSmartRefreshLayout.setNestedScrollingEnabled(false);
        mSmartRefreshLayout.setOnLoadMoreListener(this);
        mSmartRefreshLayout.setOnRefreshListener(this);
    }

    private void initAdapter() {
        GridLayoutManager manager = new GridLayoutManager(getContext(), 2);
        mRecyclerView.setLayoutManager(manager);
        mRecomAdapter = new RecomAdapter(mContext,mDishList);
        mRecyclerView.setAdapter(mRecomAdapter);
        mRecomAdapter.setOnItemClickListener(new RecomAdapter.onItemClickListener() {
            @Override
            public void onSeleClickListener(View view, int position) {
                Intent intent = new Intent(getActivity(), DishDetailActivity.class);
                intent.putExtra("dishId",mDishList.get(position).dishId);
                Dish dish = mDishList.get(position);

                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
    }

    @Override
    protected RecomPresenter createPresenter() {
        return new RecomPresenter();
    }

    @Override
    public void onLoadDish(List<Dish> dishList) {
        mDishList.clear();
        mDishList.addAll(dishList);
        mRecomAdapter.setDishList(mDishList);
    }

    @Override
    public void onRefreshDish(List<Dish> dishList) {
        mDishList.clear();
        mDishList.addAll(0,dishList);
        mRecomAdapter.setDishList(mDishList);
    }

    public void startLoadingView() {
        Event e = new Event();
        e.target = Event.TARGET_MAIN;
        e.type = Event.TYPE_START_ANIMATION;
        EventBus.getDefault().post(e);
    }

    public void stopLoadingView() {
        Event e = new Event();
        e.target = Event.TARGET_MAIN;
        e.type = Event.TYPE_STOP_ANIMATION;
        EventBus.getDefault().post(e);
    }


    @Override
    public void onLoading() {
        startLoadingView();
    }

    @Override
    public void onLoadingFailed() {

//        ToastUtils.showShort("加载失败");
    }

    @Override
    public void onLoadSuccess() {
//        ToastUtils.showShort("success");
        stopLoadingView();
        mSmartRefreshLayout.finishLoadMore();
        mSmartRefreshLayout.finishRefresh();
    }

    @Override
    public void onCollect(ToAddCollectData collectData, int dishId) {
        if(collectData != null){
            if(collectData.getCode() == 1){
                Utils.showSnackMessage(getActivity(),"收藏成功");
            } else {
                ToastUtils.showShort("收藏失败");
            }
        }
    }

    @Override
    public void onUnCollect(ToAddCollectData collectData, int dishId) {
        if(collectData != null){
            if(collectData.getCode() == 1){
                Utils.showSnackMessage(getActivity(),"取消收藏成功");
            } else {
                ToastUtils.showShort("取消收藏失败");
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(Event event){
        if(event.target == Event.TARGET_RECOM){
            if(event.type == Event.TYPE_COLLECT){
                Integer dishId = Integer.valueOf(event.data);
                //修改dish中id字段为1--收藏
                mDishList.stream().filter(dish ->
                        dish.id == dishId)
                        .findFirst().get().collect = 1;
                mRecomAdapter.notifyDataSetChanged();
                mPresenter.collect(userId,dishId);
            } else if(event.type == Event.TYPE_UNCOLLECT){
                Integer dishId = Integer.valueOf(event.data);
                mDishList.stream().filter(dish ->
                        dish.id == dishId)
                        .findFirst().get().collect = 0;
                mRecomAdapter.notifyDataSetChanged();
                mPresenter.unCollect(userId,dishId);
            }
        }
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        currentPage++;
        mPresenter.loadDish(currentPage);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        currentPage = 1;
        mPresenter.refreshDish(currentPage);
    }
}
